package com.leyou.user.interceptors;

import com.leyou.common.auth.pojo.AppInfo;
import com.leyou.common.auth.pojo.Payload;
import com.leyou.common.auth.utils.JwtUtils;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exceptions.LyException;
import com.leyou.user.config.JwtProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * @author 虎哥
 */
@Slf4j
public class AppPrivilegeInterceptor implements HandlerInterceptor {

    private JwtProperties prop;

    public AppPrivilegeInterceptor(JwtProperties prop) {
        this.prop = prop;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        // 获取请求头中的token
        String token = request.getHeader(prop.getApp().getHeaderName());
        // 验证和解析token
        Payload<AppInfo> payload = JwtUtils.getInfoFromToken(token, prop.getPublicKey(), AppInfo.class);
        // 如果通过，说明时自己人，但是还要校验权限，获取targetList
        AppInfo appInfo = payload.getUserInfo();
        List<Long> targetList = appInfo.getTargetList();
        // 判断是否包含当前服务
        if(!targetList.contains(prop.getApp().getId())){
            // 没有当前服务的访问权限
            log.info("服务非法访问，没有权限。访问者：{}， 服务名称：{}", request.getRemoteHost(), appInfo.getServiceName());
            throw new LyException(ExceptionEnum.FORBIDDEN);
        }
        return true;
    }
}
